<!--
 @description
 @fileName Filter.vue
 @author zengqiongying
 @created 2022/08/08 13:24:58
-->
<template>
  <div class="order-filter">
    <div class="search-pan">
      <SearchInput v-model="searchValue" @search="handleSearch" />
    </div>
    <div v-if="filterData.length>0" class="filter-bar" @click.stop="closeHandle">
      <Item
        ref="item"
        :list="listItem"
        :index.sync="filterIndex"
        :flag.sync="filterFlag"
        @click.native.stop
      />
      <div v-show="filterIndex!==null" class="filter-mask" @click.stop="closeHandle">
        <Scroll vertical class="scroll-height" @click.native.stop>
          <div class="filter-content">
            <Card :show-btn="filterFlag==='filter' || (activeFilter && activeFilter.multiple)" @reset="resetHandle" @confirm="confirmHandle">
              <template v-for="(f,i) in filtersView">
                <div
                  v-if="filterIndex!==null&&!isFilterSort"
                  :key="i"
                  :class="['filter-content-item',{'filter-content-clown':!(activeFilter && activeFilter.multiple)},{'filter-content-item-selected':f.selected}]"
                  @click.stop="selectedClick(f, filtersView)"
                >
                  <span class="filter-content-text">{{ f.dictName }}</span>
                  <img v-show="f.selected" class="filter-content-img" :src="sectionImg">
                </div>
                <template v-else-if="filterFlag==='filter'">
                  <div :key="i" class="filter-content-title" row>
                    <span>{{ f.title }}</span>
                    <div @click.stop="foldClickHandle(f)">
                      <span>{{ isFold(f)?'更多':'收起' }}</span>
                      <svg-icon :icon-class="isFold(f)?'xiangxia-zhankai-line':'xiangshang-shouqi-line'" />
                    </div>
                  </div>
                  <template v-if="!isFold(f)">
                    <template v-if="f.type=='daterange'">
                      <div :key="f.flag + i" class="filter-content-field" row>
                        <van-field v-model="f.value1" class="cus-field" label="" left-icon="calendar-o" readonly placeholder="选择日期" @click.native="openCaledar(f)" />
                        <div class="separator" />
                        <van-field v-model="f.value2" class="cus-field" label="" left-icon="calendar-o" readonly placeholder="选择日期" @click.native="openCaledar(f)" />
                      </div>
                    </template>
                    <template v-if="f.type=='text'">
                      <div :key="f.flag + i" class="filter-content-field" row>
                        <van-field v-model="f.value" class="cus-field" label="" placeholder="请输入" />
                      </div>
                    </template>
                    <template v-else>
                      <div
                        v-for="(c,m) in f.children || []"
                        :key="c.dictName + m"
                        :class="['filter-content-item',{'filter-content-item-selected':c.selected}]"
                        @click.stop="selectedClick(c, f)"
                      >
                        <span class="filter-content-text">{{ c.dictName }}</span>
                      <!-- <img v-show="c.selected" class="filter-content-img" :src="sectionImg"> -->
                      </div>
                    </template>
                  </template>
                </template>
                <template v-else-if="filterFlag==='sort'">
                  排序
                </template>
              </template>
            </Card>
          </div>
        </Scroll>
      </div>
    </div>
    <van-calendar
      v-model="caledar.show"
      type="range"
      color="#05C4C3"
      :title="caledar.field==='saleDate'?'零售日期':'制单日期'"
      :min-date="caledarMinDate"
      :max-date="caledarMaxDate"
      :default-date="caledar.defaultData"
      :style="{'height':'500px'}"
      allow-same-day
      @confirm="onConfirmCaledar"
    />
  </div>
</template>

<script>
import Scroll from '@/components/Scroll'
import Card from './Card'
import Item from './Item'
import SearchInput from '../SearchInput'
import sectionImg from '@/assets/icon-yes.png'
import { getDictByType, getDictByPatchType } from '@/apis/dataDict'
import { parseTime } from '@/utils'
export default {
  name: 'OrderFilter',
  components: {
    SearchInput, Scroll, Card, Item
  },
  props: {
    dictData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      searchValue: '',
      caledarMinDate: '',
      caledarMaxDate: '',
      caledar: {
        show: false,
        field: '', // 当前字段
        defaultData: []
      },
      sectionImg,
      filterIndex: null,
      filterFlag: null,
      // 临时记录本次选择，如果不点确定则关闭弹窗时清楚
      tempFiltersValue: [],
      filterData: [
        { title: '来源', flag: 'orderSource', show: true, multiple: true, children: [] },
        { title: '订单状态', flag: 'state', show: true, multiple: true, children: [] },
        { title: '收款状态', flag: 'paymentState', show: true, multiple: true, children: [] },
        { title: '制单日期', flag: 'createTime', show: false, type: 'daterange', value1: '', value2: '' },
        { title: '销售日期', flag: 'saleDate', show: false, type: 'daterange', value1: '', value2: '' }
        // { title: '测试输入', flag: 'name', show: false, type: 'text', value: '' }
      ]
    }
  },

  computed: {
    activeFilter() {
      return this.filterData.find(v => v.flag === this.filterFlag)
    },
    listItem() {
      return this.filterData.filter(v => !!v.show)
    },
    // 过滤
    isFilterSort() {
      return ['filter'].includes(this.filterFlag)
    },

    filtersView() {
      let result
      if (/^\d+$/.test(this.filterIndex) && !this.isFilterSort) {
        result = this.listItem[this.filterIndex].children
      } else if (this.filterFlag === 'filter') {
        result = this.filterData
      } else {
        result = []
      }
      return result
    }
  },
  watch: {
    dictData: {
      handler(val, old) {
        this.updateFilterData()
      },
      deep: true,
      immediate: true
    },
    filterIndex(n) {
      if (n === null) {
        this.recoverSelected()
      }
      this.limitScroll()
    }
  },

  created() {
    const date = new Date()
    const mDate = date.setFullYear(date.getFullYear() - 6)
    this.caledarMinDate = new Date(mDate)
    this.caledarMaxDate = new Date()
  },
  activated() {},

  mounted() {},

  methods: {
    // TODO : 请求数据 获取数据字典值
    async getDictList() {
      const appCode = 'retail'
      const sourceList = await getDictByType({ appCode, dictTypeCode: 'ORDER_SOURCE' })
      const statusList = await getDictByType({ appCode, dictTypeCode: 'STATUS' })
      const paymentStateList = [
        { dictCode: '01', dictName: '未结清' },
        { dictCode: '02', dictName: '已结清' }
      ]
      sourceList.forEach(v => {
        if (v.dictCode === '02') {
          v.selected = true
        }
      })
      this.$set(this.filterData[0], 'children', sourceList)
      this.$set(this.filterData[1], 'children', statusList)
      this.$set(this.filterData[2], 'children', paymentStateList)
    },
    updateFilterData() {
      // 订单来源默认选中 02 销售宝
      const sourceDict = this.$deepCopy(this.dictData['ORDER_SOURCE'] || [])
      const sourceList = sourceDict.map(v => {
        if (v.dictCode === '02') {
          return { ...v, ...{ selected: true }}
        } else {
          return v
        }
      })
      const statusDict = this.$deepCopy(this.dictData['STATUS'] || [])
      const statusList = statusDict.map(v => {
        return v
      })
      const paymentStateList = [
        { dictCode: '01', dictName: '未结清' },
        { dictCode: '02', dictName: '已结清' }
      ]
      this.$set(this.filterData[0], 'children', sourceList)
      this.$set(this.filterData[1], 'children', statusList)
      this.$set(this.filterData[2], 'children', paymentStateList)
    },
    handleSearch(data) {
      const { type, value } = data
      if (value === '') {
        this.$toast(`请输入${type === 'code' ? '零售单号' : '顾客姓名'}`)
        return
      }
      this.$router.push({
        path: '/my/orderSearch',
        query: {
          searchType: type,
          searchVal: value
        }
      })
    },
    // 去掉所有
    cancelSelectedAll(list, type) {
      for (const item of list) {
        delete item.fold // 重置折叠收起
        if (item.selected) {
          this.tempFiltersValue.push({
            filter: item,
            rawValue: item.selected,
            value: false
          })
        }
        this.$set(item, 'selected', false)
        const children = item.children || item.next
        if (children instanceof Array) {
          this.cancelSelectedAll(children, type)
        }
        if (item.type === 'daterange') {
          this.$set(item, 'value1', '')
          this.$set(item, 'value2', '')
        } else if (item.type === 'text') {
          this.$set(item, 'value', '')
        }
      }
    },
    // 展开收起
    foldClickHandle(f) {
      if (f.fold) {
        this.$set(f, 'fold', false)
      } else {
        this.$set(f, 'fold', true)
      }
    },
    // 是否折叠
    isFold(f) {
      if (f.fold === undefined) {
        if (f.isDefaultFolded === 1 || f.isDefaultFolded === '1') {
          // 如果fold不存在且isDefaultFolded等于1则设置fold值，解决单击更多，收起的bug
          this.$set(f, 'fold', true)
          return true
        }
        return false
      }
      return f.fold
    },
    // 选中
    selectedClick(f, obj) {
      let multiple = true
      let list = obj
      if (this.$isType(obj, 'Array') && !this.isFilterSort && /^\d+$/.test(this.filterIndex)) {
        multiple = !!((this.listItem[this.filterIndex] || {}).multiple)
      } else if (this.isFilterSort && this.filterFlag === 'filter') {
        multiple = !!obj.multiple
        list = obj.children
      }
      const rawSelected = f.selected
      if (!multiple && this.$isType(list, 'Array')) {
        this.cancelSelectedAll(list)
      }

      if (rawSelected) {
        this.$set(f, 'selected', false)
        this.tempFiltersValue.push({
          filter: f,
          rawValue: true,
          value: false
        })
      } else {
        this.$set(f, 'selected', true)
        this.tempFiltersValue.push({
          filter: f,
          rawValue: false,
          value: true
        })
      }
    },
    // 重置选择
    resetHandle() {
      if (!this.isFilterSort) {
        this.cancelSelectedAll(this.listItem[this.filterIndex].children)
      } else if (this.filterFlag === 'filter') {
        this.cancelSelectedAll(this.filtersView)
      }
      this.tempFiltersValue = []
    },
    // 还原选中
    recoverSelected() {
      for (const t of this.tempFiltersValue) {
        this.$set(t.filter, 'selected', t.rawValue)
      }
      this.tempFiltersValue = []
    },
    // 单击背景关闭
    closeHandle() {
      this.recoverSelected()
      this.filterIndex = null
      this.filterFlag = null
      if (this.$refs.item) {
        this.$refs.item.closeFlag()
      }
    },
    // 确定筛选
    confirmHandle() {
      const params = {}
      this.filterData.forEach(v => {
        const key = v.flag
        if (key !== 'filter') {
          let value = []
          if (v.type === 'daterange') {
            if (v.value1 && v.value2) {
              value = [v.value1, v.value2]
            }
          } else {
            value = v.children.filter(c => c.selected).map(d => d.dictCode)
          }
          if (value.length > 0) {
            params[key] = value
          }
        }
      })
      this.$emit('refresh', params)

      this.tempFiltersValue = []
      this.filterIndex = null
      this.filterFlag = null
      this.$refs.item.closeFlag()
    },
    // 限制滚动
    limitScroll() {
      if (this.filterIndex !== null) {
        document.body.classList.add('limit-scroll')
      } else {
        document.body.classList.remove('limit-scroll')
      }
    },
    // 打开日历选择器
    openCaledar(f) {
      let defVal = []
      if (f.value1 && f.value2) {
        defVal = [new Date(f.value1), new Date(f.value2)]
      }
      if (defVal.length === 0) {
        const d = new Date()
        defVal = [d, d]
      }
      this.caledar = {
        show: true,
        field: f.flag,
        defaultData: defVal
      }
    },
    // 确认日历选择
    onConfirmCaledar(date) {
      const [start, end] = date
      const value1 = parseTime(start, '{y}-{m}-{d}')
      const value2 = parseTime(end, '{y}-{m}-{d}')
      const field = this.caledar.field
      const index = this.filterData.findIndex(v => v.flag === field)
      this.$set(this.filterData[index], 'value1', value1)
      this.$set(this.filterData[index], 'value2', value2)

      // this.selectedClick(this.filterData[index], this.filtersView)
      this.$nextTick(() => {
        this.caledar = {
          show: false,
          field: '',
          defaultData: []
        }
      })
    }
  }
}

</script>
<style lang='less' scoped>
  .order-filter{
    background: #fff;
    height: 126px;
    .search-pan{
      padding: 18px 16px 12px;
    }
  }
  // 筛选项
  .filter-bar{
    z-index: 99;
    .filter-mask{
      height: calc(100vh - 44PX - 126px);
      background:rgba(0, 0, 0, .7)
    }
    .scroll-height{
      background-color: #fff;
      max-height: calc(100vh - 44PX - 126px - 90px);
      border-radius: 0px 0px 12px 12px;
      overflow-y: auto;
    }
    .filter-content{
      min-height: 100px;
      background-color: #fff;
      .filter-content-item{
        position: relative;
        height: 100%;
        width: 100%;
        text-align: center;
        box-sizing: border-box;
        background-color:rgba(241, 241, 242, .5);
        border-radius: 12px;
        overflow: hidden;
        .filter-content-text{
          flex: 0 0 auto;
          padding: 0 10px;
          font-size: 12px;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: block;
        }
        .filter-content-img{
          width: 16px;
          height: 11px;
        }
        &.filter-content-item-selected{
          background: rgba(0, 200, 180,.1);
          .filter-content-text{
            color: #00C8B4;
          }
        }
        &.filter-content-clown{
          position: relative;
          padding: 0 10px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 41px;
          box-sizing:border-box;
          background: #fff;
          border-radius:0;
          &::after{
            content: '';
            position: absolute;
            left: 10px;
            right: 10px;
            bottom: 0;
            height: 1px;
            background: rgba(0, 0, 0, 0.1);
          }
          &:last-child::after{
            height: 0;
          }
          .filter-content-text{
            font-weight: normal;
            font-size: 14px;
            color: #3C4458;
          }
        }
      }
      // 展开收起
      .filter-content-title{
        display: flex;
        justify-content: space-between;
        align-items: center;
        &>div{
          color: #888;
          font-size: 12px;
          &>svg{
            color: inherit;
            font-size: inherit;
            margin-left: 2px;
          }
        }
      }
    }
    .filter-content-field{
      padding: 0  0 0 10px !important;
      width: 100%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .cus-field{
        flex: 1;
        height: 36px;
        line-height: 1;
        background: rgba(241, 241, 242, .5);
      }
      .separator{
        margin: 0 16px;
        width: 23px;
        height: 2px;
        background: #B5B7C4;
        border-radius: 1px;
      }
    }
  }
</style>
<style>
  .limit-scroll{
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    overflow: hidden !important;
  }
</style>

